<template>
  <div>
    <div class="row">
      <div class="col-sm-12 col-md-12">
        <div class="card bg-dark text-white">
          <img src="/img/team.jpg" height="200" class="d-md-inline d-sm-none" alt="...">
          <div class="card-img-overlay d-flex flex-column justify-content-center align-items-center">
            <h5 class="card-title">在线智能服务组队平台</h5>
            <p>
              <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#staticBackdrop"
                      @click="sendApplyTeam">发起组队
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>

    <div class="row mt-3">
      <div class="col">
        <div class="card">
          <div class="card-body">
            <div class="row">
              <div class="col-md-8 col-sm-12">
                <div class="raceType">
                  <span>分类：</span>
                  <span class="link active" @click="GetUserAllTeam('null',searchForm.collegeName)">全部</span>
                  <span class="link" @click="GetUserAllTeam(0,searchForm.collegeName)">可加入</span>
                  <span class="link" @click="GetUserAllTeam(1,searchForm.collegeName)">已满员</span>
                </div>
                <div class="raceType">
                  <span>学院：</span>
                  <span class="genre active"
                        @click="GetUserAllTeam('null',undefined,$event)">全部</span>
                  <template v-for="(el,index) in genreArr">
                              <span class="genre" v-bind:key="index"
                                    @click="GetUserAllTeam(searchForm.status,el._id,$event)">{{
                                  el._id[0]|college
                                }}</span>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-1 mt-2 mb-3">
      <template v-if="teamData.length!==0">
        <template v-for="el in teamData">
          <div :key="el._id" class="col-md-4 col-sm-12">
            <div class="card">
              <div class="card-body" style="font-size: 14px">
                <h5 class="card-title">{{ el.name }}</h5>
                <p class="card-text">
                  <span class="contest-name" @click="ContestDetail(el.contestID)">{{ el.contest[0].name }}</span>
                </p>
                <p>
                  <span class="ms-3">发起者：{{ el.children[0].userName }}</span>
                  <span class="ms-3">人数限制：{{ `${el.children.length}/${el.num}` }}</span>
                </p>
                <div class="d-grid gap-2">
                  <button class="btn  btn-primary" type="button" @click="TeamDetail(el._id)">查看详情</button>
                  <button class="btn btn-primary" :disabled="el.status === 1" data-bs-toggle="modal"
                          data-bs-target="#staticBackdrop" type="button" @click="joinTeam(el)">申请加入
                  </button>
                </div>
              </div>
            </div>
          </div>
        </template>
      </template>
      <template v-else>
        <div class="col">
          <el-empty class="border" description="暂无竞赛"></el-empty>
        </div>
      </template>
    </div>


    <!--   模态框 -->
    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
         aria-labelledby="staticBackdropLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="staticBackdropLabel">{{ modelTitle }}</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <template v-if="isVisibleForm">
              <el-form :model="teamForm" :rules="rules" ref="teamForm" label-width="100px"
                       class="demo-ruleForm">
                <el-form-item label="团队名称" prop="name">
                  <el-input v-model="teamForm.name"></el-input>
                </el-form-item>
                <el-form-item label="组队人数" prop="num">
                  <el-input v-model.number="teamForm.num"></el-input>
                </el-form-item>
                <el-form-item label="竞赛名称" prop="value">
                  <el-select v-model="teamForm.value" placeholder="请选择">
                    <el-option
                        v-for="item in contest"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </template>
            <template v-else>
              {{ modelBody }}
            </template>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <template v-if="isVisibleForm">
              <button type="button" class="btn btn-primary" @click="confirmTeam">确认发起</button>
            </template>
            <template v-else>
              <button type="button" class="btn btn-primary" data-bs-dismiss="modal">确认</button>
            </template>
          </div>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import sex from "../../../filter/sex";
import time from "../../../filter/time";
import user from "../../../api/user";
import children from "../../../filter/children";
import college from "../../../filter/college";

export default {
  name: "myApply",
  data() {
    var checkNum = (rule, value, callback) => {
      if (Number(value) < 3 || Number(value) > 8) {
        callback(new Error("人数在3到8人"))
      } else if (value === "") {
        callback(new Error("请输入队伍人数"))
      } else {
        callback()
      }
    }
    return {
      //分页数据
      limit: 5,
      skip: 0,
      page: 1,
      size: 30,
      total: 1,

      // 组队表单
      teamForm: {
        name: '',
        num: '',
        value: ''
      },

      // 搜索表单
      searchForm: {
        status: 'null',
        collegeName: undefined,
      },


      isVisibleForm: false,
      modelTitle: '',

      genreArr: [],

      // 队伍数据

      teamData: [],


      modelBody: '您还没有报名团队赛，请先报名！',
      rules: {
        name: [
          {required: true, message: '请输入团队名称', trigger: 'blur'},
          {min: 2, max: 5, message: '长度在 3 到 8 个字符', trigger: 'blur'}
        ],
        num: [
          {validator: checkNum, trigger: 'blur'},
          {type: 'number', message: '年龄必须为数字值'}
        ],
        value: [
          {required: true, message: '请选择报名竞赛', trigger: 'change'}
        ]
      },
      userID: ''
    }
  },
  filters: {
    sex,
    time,
    children,
    college
  },
  components: {},
  mounted() {
    this.GetUserAllTeam('null')
    this.GetTeamCollege()
    this.initBtn()
  },
  methods: {

    //队伍详情
    TeamDetail(id){
      localStorage.setItem("id",JSON.stringify(id))
      this.$router.push("/TeamDetail")
    },

    // 获取各学院的队伍
    GetTeamCollege() {
      user.GetTeamCollege().then(r => {
        this.genreArr = r.data.data.tm
      })
    },

    // 竞赛详细页面
    ContestDetail(id) {
      localStorage.setItem("detailId", JSON.stringify(id))
      this.$router.push("/detail")
    },
    initBtn() {
      const span = document.querySelectorAll(".link")
      span.forEach(s => {
        s.addEventListener('click', () => {
          span.forEach(v => {
            v.classList.remove("active")
          })
          s.classList.add("active")
        })
      })
    },

    // 获取全部队伍
    GetUserAllTeam(status, college, e) {
      if (e) {
        const g = document.querySelectorAll(".genre")
        g.forEach(v => {
          v.classList.remove("active")
        })
        e.target.classList.add("active")
      }
      this.searchForm.status = status
      this.searchForm.collegeName = college
      const param = {
        limit: this.limit,
        skip: (this.page - 1) * this.size,
        status: this.searchForm.status,
        collegeName: this.searchForm.collegeName
      }
      user.GetUserAllTeam(param).then(r => {
        this.teamData = r.data.data.tm
      })
    },
    // 加入队伍
    joinTeam(el) {
      if (this.$store.getters["userStore/userInfo"].status !== 0) {
        this.isVisibleForm = false
        const param = {
          teamID: el._id,
          userID: el.children[0].userID,
          applyID: this.$store.getters["userStore/userInfo"]._id
        }
        const children = el.children
        let flag = false
        children.some(c => {
          if (this.$store.getters["userStore/userInfo"]._id === c.userID) {
            flag = true
          }
        })
        if (flag) {
          this.isVisibleForm = false
          this.modelTitle = "温馨提示"
          this.modelBody = "您已经加入该队伍"
        } else if (children.length === el.num) {
          this.isVisibleForm = false
          this.modelTitle = "温馨提示"
          this.modelBody = "人数已满"
        } else {
          const loading = this.$loading({
            lock: true,
            text: '正在申请加入',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          user.joinTeam(param).then(r => {
            if (r.status === 200) {
              loading.close();
              this.isVisibleForm = false
              this.modelTitle = "温馨提示"
              this.modelBody = "申请成功"
            }
          })
        }
      } else {
        this.isVisibleForm = false
        this.modelTitle = "温馨提示"
        this.modelBody = "您的信息未认证，请先到个人中心认证"
      }
    },
    // 发起组队
    sendApplyTeam() {
      user.GetApplyAndRaceType().then(r => {
        if (r.data.data.result.length === 0) {
          this.isVisibleForm = false
          this.modelTitle = "温馨提示"
          this.modelBody = "您还没有报名团队赛，请先报名！"
        } else {
          this.modelTitle = "在线发起组队"
          this.isVisibleForm = true
          this.contest = r.data.data.result
        }
      })
    },
    confirmTeam() {
      this.$refs.teamForm.validate(v => {
        if (v) {
          const param = {...this.teamForm}
          user.ApplyTeamConfirm(param).then(r => {
            if (r.data.status === "200" && r.data.data.msg === '') {
              this.$message({
                message: '组队成功',
                type: 'success'
              });
              this.GetAllTeam()
            } else {
              this.$message({
                message: '队伍已存在',
                type: 'error'
              });
            }
          })
        } else {
          return false;
        }
      })
    }
  }
}
</script>

<style scoped>

.raceType:not(:first-child) {
  margin-top: 20px;
}

.raceType > span:not(:first-child) {
  margin-left: 15px;
}

.contest-name:hover {
  text-decoration: underline;
  color: #40aaff;
  cursor: pointer;
}

.link, .genre {
  cursor: pointer;
}

.active {
  color: #40aaff;
}
</style>